package com.jboost.modules.system.controller;


import cn.hutool.core.collection.CollUtil;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jboost.common.api.vo.Result;
import com.jboost.common.constant.CommonConstant;
import com.jboost.common.domain.DomainConstant;
import com.jboost.common.system.api.ISysBaseAPI;
import com.jboost.common.system.query.QueryGenerator;
import com.jboost.common.system.vo.DictModel;
import com.jboost.common.system.vo.LoginUser;
import com.jboost.common.util.RedisUtil;
import com.jboost.modules.base.service.BaseCommonService;
import com.jboost.modules.file.service.IJboostFileService;
import com.jboost.modules.system.entity.SysAccount;
import com.jboost.modules.system.entity.SysUser;
import com.jboost.modules.system.service.*;
import com.jboost.modules.system.vo.SysUserAccountVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 账号表 前端控制器
 * </p>
 *
 * @Author scott
 * @since 2018-12-20
 */
@Slf4j
@RestController
@RequestMapping("/sys/account")
public class SysAccountController {
    public static String BASE_PSW_CODES = "qwertyuiplkjhgfdsazxcvbnm1234567890";
    public static final String INIT_DEPART_CODE = "CC_INIT";
	@Autowired
	private ISysBaseAPI sysBaseAPI;

	@Autowired
	private ISysAccountService sysAccountService;

	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private ISysDictService sysDictService;

    @Autowired
    private ISysDepartService sysDepartService;

    @Autowired
    private ISysDepartRoleUserService departRoleUserService;

    @Autowired
    private ISysDepartRoleService departRoleService;

	@Autowired
	private RedisUtil redisUtil;

    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    @Resource
    private BaseCommonService baseCommonService;
    @Autowired
    private IJboostFileService fileService;


    /**
     * 获取账号列表数据
     * @param account
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public Result<IPage<SysAccount>> queryPageList(SysAccount account,@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,HttpServletRequest req) {
		Result<IPage<SysAccount>> result = new Result<IPage<SysAccount>>();
//		account.setPhone(account.getUsername());
//		account.setRealname(account.getUsername());
		QueryWrapper<SysAccount> queryWrapper = QueryGenerator.initQueryWrapper(account, req.getParameterMap());
		Page<SysAccount> page = new Page<SysAccount>(pageNo, pageSize);
		IPage<SysAccount> pageList = sysAccountService.page(page, queryWrapper);

		//批量查询账号的所属部门
        //step.1 先拿到全部的 useids
        //step.2 通过 useids，一次性查询账号的所属部门名字
        List<String> accountIds = pageList.getRecords().stream().map(SysAccount::getId).collect(Collectors.toList());
//        if(accountIds!=null && accountIds.size()>0){
//            Map<String,String>  useDepNames = sysUserService.getDepNamesByUserIds(accountIds);
//            pageList.getRecords().forEach(item->{
//                item.setOrgCodeTxt(useDepNames.get(item.getId()));
//            });
//        }
        //查角色

		result.setSuccess(true);
		result.setResult(pageList);
		log.info(pageList.toString());
		return result;
	}

    //@RequiresRoles({"admin"})
    //@RequiresPermissions("account:add")
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public Result<SysAccount> add(@RequestBody JSONObject jsonObject) {
		Result<SysAccount> result = new Result<SysAccount>();

		return result;
	}

    //@RequiresRoles({"admin"})
    //@RequiresPermissions("account:edit")
	@RequestMapping(value = "/edit", method = RequestMethod.PUT)
	public Result<SysAccount> edit(@RequestBody JSONObject jsonObject) {
		Result<SysAccount> result = new Result<SysAccount>();

		return result;
	}

	/**
	 * 删除账号
	 */
	//@RequiresRoles({"admin"})
	@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		return Result.ok("删除账号成功");
	}

	/**
	 * 批量删除账号
	 */
	//@RequiresRoles({"admin"})
	@RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		return Result.ok("批量删除账号成功");
	}

	/**
	  * 冻结&解冻账号
	 * @param jsonObject
	 * @return
	 */
	//@RequiresRoles({"admin"})
	@RequestMapping(value = "/frozenBatch", method = RequestMethod.PUT)
	public Result<SysAccount> frozenBatch(@RequestBody JSONObject jsonObject) {
		Result<SysAccount> result = new Result<SysAccount>();
		return result;

    }

    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result<SysAccount> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<SysAccount> result = new Result<SysAccount>();
        return result;
    }

    @RequestMapping(value = "/userList", method = RequestMethod.GET)
    public Result<List<SysUser>> userList() {
		Result<List<SysUser>> result = new Result<List<SysUser>>();
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if(user==null || StringUtils.isEmpty(user.getUsername())){
			return result.error500("用户或用户名为空！");
		}
		List<DictModel> modelList = sysDictService.queryDictItemsByCode(CommonConstant.DOMAIN_DICT_CODE);
		List<SysUser> userList = sysUserService.getUserListByName(user.getUsername());
		List<SysUser> newUserList = userList.stream().map(u->{
			List<String> roles = sysUserService.getRoleById(u.getId());
			u.setRoleNameList(roles);
//			DictModel dictModel = null;
//			try {
//				dictModel = modelList.stream().filter(dict -> dict.getValue().equals( u.getDomain() )).findFirst().get();
//			}catch (NoSuchElementException e){
//				dictModel = new DictModel();
//			}
//			u.setDomainName(dictModel.getText());
//			u.setDomainUrl(dictModel.getDescription());
			return u;
		}).collect(Collectors.toList());
		result.setResult( newUserList );
        return result;
    }

	/**
	 * 根据账户ID查询产品域用户列表
	 * @param accountId
	 * @return
	 */
	@GetMapping("/user/list")
	public Result<?> getUserListByAccountId(String accountId) {
		List<SysUserAccountVo> allUserByAccountId = sysAccountService.getAllUserByAccountId(accountId);
		if (CollUtil.isEmpty(allUserByAccountId)) {
			return Result.OK(allUserByAccountId);
		}
		for (SysUserAccountVo s : allUserByAccountId) {
			if (DomainConstant.BUSINESS.getCode().equals(s.getDomain())) {
				s.setDomain(DomainConstant.BUSINESS.getDescription());
			}else if (DomainConstant.OPERATION.getCode().equals(s.getDomain())) {
				s.setDomain(DomainConstant.OPERATION.getDescription());
			}
		}
		return Result.OK(allUserByAccountId);
	}
}
